package com.cc.dingtalk;

import com.cc.model.vo.InventoryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author CC
 * @version 1.0
 * @description: 钉钉消息服务
 * @date 2025/10/14 16:09
 */
@Component
@Slf4j
public class DingTalkService {
    @Autowired
    private SendDingService sendDingService;
    // 前端地址
    @Value("${front-url}")
    private static String FRONT_URL;
    /**
     * 简化版本 - 发送库存预警到钉钉
     */
    public void sendInventoryWarning(List<InventoryVo> inventoryList) {
        if (inventoryList == null || inventoryList.isEmpty()) {
            return;
        }

        StringBuilder sb = new StringBuilder();

        // 标题
        sb.append("## 🚨 库存预警通知\n\n");

        // 统计信息
        sb.append("📊 **发现 ").append(inventoryList.size()).append(" 个商品库存不足**\n\n");

        // 表格标题
        sb.append("### 📋 库存详情\n");
        sb.append("| 商品名称 | 当前库存 | 安全库存 | 缺货量 | 状态 |\n");
        sb.append("| :--- | :---: | :---: | :---: | :---: |\n");

        // 表格内容
        for (InventoryVo item : inventoryList) {
            int shortage = item.getSafeQuantity() - item.getQuantity();
            String status;
            if (item.getQuantity() == 0) {
                status = "🔴 缺货";
            } else if (shortage > 20) {
                status = "🟠 严重";
            } else if (shortage > 10) {
                status = "🟡 不足";
            } else {
                status = "🔵 提醒";
            }

            sb.append(String.format("| %s | %d | %d | **%d** | %s |\n",
                    item.getProductName(),
                    item.getQuantity(),
                    item.getSafeQuantity(),
                    shortage,
                    status));
        }

        sb.append("\n");
        sb.append("> 💡 请及时补充库存\n");
        sb.append("> ⏰ ").append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

//        SendRequestParam.Markdown markdown = new SendRequestParam.Markdown();
//        markdown.setText(sb.toString());
//        markdown.setTitle("库存预警通知");

//        SendRequestParam.Link link = new SendRequestParam.Link();
//        link.setText(sb.toString());
//        link.setMessageUrl("http://127.0.0.1:5500/%E5%BA%93%E5%AD%98%E5%B1%95%E7%A4%BA.html");
//        link.setTitle("库存预警通知");
        SendRequestParam.ActionCard actionCard = new SendRequestParam.ActionCard();
        actionCard.setTitle("库存预警通知");
        actionCard.setText(sb.toString());
        actionCard.setSingleTitle("查看详情");
        actionCard.setSingleURL(FRONT_URL);
        sendDingService.sendActionCard(actionCard).send();
    }
}